package com.anne.fish.webapp.action;

import com.opensymphony.xwork2.Preparable;
import com.anne.fish.service.CatManager;
import com.anne.fish.model.Cat;
import com.anne.fish.webapp.action.BaseAction;

import java.util.List;

public class CatAction extends BaseAction implements Preparable {
    private CatManager catManager;
    private List cats;
    private Cat cat;
    private Long id;
    private String query;

    public void setCatManager(CatManager catManager) {
        this.catManager = catManager;
    }

    public List getCats() {
        return cats;
    }

    
    /**
     * Grab the entity from the database before populating with request parameters
     */
    public void prepare() {
        if (getRequest().getMethod().equalsIgnoreCase("post")) {
            // prevent failures on new
            String catId = getRequest().getParameter("cat.id");
            if (catId != null && !catId.equals("")) {
                cat = catManager.get(new Long(catId));
            }
        }
    }

    public void setQ(String q) {
        this.query = q;
    }

    public String list() {
        cats = catManager.search(query, Cat.class);
        return SUCCESS;
    }
    
    public String listSub(){
    	cats = this.catManager.findByFatherId(id);
    	return SUCCESS;
    }
    

    public void setId(Long id) {
        this.id = id;
    }

    public Cat getCat() {
        return cat;
    }

    public void setCat(Cat cat) {
        this.cat = cat;
    }

    public String delete() {
        catManager.remove(cat.getId());
        saveMessage(getText("cat.deleted"));

        return SUCCESS;
    }

    public String edit() {
        if (id != null) {
            cat = catManager.get(id);
        } else {
            cat = new Cat();
        }

        return SUCCESS;
    }

    public String save() throws Exception {
        if (cancel != null) {
            return "cancel";
        }

        if (delete != null) {
            return delete();
        }

        boolean isNew = (cat.getId() == null);

        catManager.save(cat);

        String key = (isNew) ? "cat.added" : "cat.updated";
        saveMessage(getText(key));

        if (!isNew) {
            return INPUT;
        } else {
            return SUCCESS;
        }
    }
}